package top.birdhk.TestAPI.state;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.*;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.shaded.zookeeper.org.apache.zookeeper.jute.CsvOutputArchive;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import top.birdhk.TestAPI.beans.SensorReading;

import java.util.Iterator;

/**
 * 键控状态
 */
public class StateTest_KeyedState {

    public static void main(String[] args) throws Exception {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();


        env.setParallelism(1);

        DataStreamSource<String> dataStream = env.readTextFile("E:\\flink\\wordcount\\src\\main\\resources\\sensor.txt");

//        DataStreamSource<String> dataStream = env.socketTextStream("localhost", 7777);


        SingleOutputStreamOperator<SensorReading> inputStream = dataStream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], new Long(split[1]), new Double(split[2]));
        });


        // 定义一个有状态的map操作，统计当前sensor数据的个数
        SingleOutputStreamOperator<Integer> mapStream = inputStream
                .keyBy("id")
                .map(new MyKeyCountMapper());


        mapStream.print("count:");

        env.execute();

    }


    public static class MyKeyCountMapper extends RichMapFunction<SensorReading,Integer>{

        private ValueState<Integer> keyCount;

        // 其他类型状态声明
        private ListState<String> myListState;

        private MapState<String,Double> myMapState;

        private ReducingState<SensorReading> myReducingState;

        @Override
        public Integer map(SensorReading sensorReading) throws Exception {
            Integer count = keyCount.value();
            count++;
            keyCount.update(count);


            // 其他状态API调用
            for (String s : myListState.get()) {
                System.out.println(s);
            }

            myListState.add("hello");

            myMapState.get("1");
            myMapState.put("2",2.2);


            // reducing state
//            myReducingState.add();

            return count;

        }

        @Override
        public void open(Configuration parameters) throws Exception {
            keyCount = getRuntimeContext().getState(new ValueStateDescriptor<Integer>("key-count",Integer.class));
            myListState = getRuntimeContext().getListState(new ListStateDescriptor<String>("my-list",String.class));
            myMapState = getRuntimeContext().getMapState(new MapStateDescriptor<String, Double>("my-map",String.class,Double.class));
//            myReducingState = getRuntimeContext().getReducingState(new ReducingStateDescriptor<SensorReading>("my-reducing",));
        }
    }

}
